import asyncio
import json
from pyppeteer import launch
from pyppeteer.network_manager import Response

from ctaxccgp.simple.slider_util import slide_move


async def open_page():
    browser = await launch(headless=False, userDataDir='E:/TempData/', ignoreDefaultArgs=['--enable-automation'])
    page = await browser.newPage()
    await page.setViewport({"width": 1440, "height": 1080})
    await page.setUserAgent(
        'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36')
    await page.evaluate('''() => {Object.defineProperty(navigator, 'webdriver', {get: () => undefined})}''')
    page.on("response", get_content)

    await page.goto('https://ctaxccgp.zcygov.cn/items/31218730')
    await page.waitForSelector('div#tab-dealrecord')
    await page.waitFor(1500)
    await page.click('div#tab-dealrecord')
    await page.waitFor(1200)

    await check_slider(page)

    await get_next_page(page)

    await page.close()


async def check_slider(page):
    slider = await page.querySelector('#nc_nvc_wrapper')
    if slider:
        is_hidden = await page.evaluate('()=>{return window.getComputedStyle(document.getElementById("nc_nvc_wrapper")).display === "none";}')
        if not is_hidden:
            print('--> slider show~')
            await slide_move(page)
    else:
        return


async def get_next_page(page):
    for page_no in range(1, 54):
        print('page: ' + str(page_no))

        # await check_slider(page)

        await page.waitForSelector('div.po-pagination input.po-input__inner'),
        await page.evaluate('document.querySelector("div.po-pagination input.po-input__inner").value=""')
        await page.type('div.po-pagination input.po-input__inner', str(page_no))
        await page.waitFor(300)
        await page.click('div.po-pagination button.btn-go')
        await page.waitFor(3000)

        await check_slider(page)


async def get_content(response: Response):
    if "front/detail/item/dealRecord" in response.url:
        url = response.url
        content = await response.text()
        js = json.loads(content)
        if js and js.get('success'):
            print('------------------')
            print(url)
            print(js)



asyncio.get_event_loop().run_until_complete(open_page())